﻿using System;
using System.Collections.Generic; 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.EShop.Bll;
using Runda.EShop.Common.Entity;

namespace Runda.EShop.Web.UserControl
{
    public partial class ProductCateTree :UserControlBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTree();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.Load += new EventHandler(Page_Load);
        }

        private void BindTree()
        {
            MasterDataBll bll = new MasterDataBll();
            List<BasProductCateEntity> dt = bll.LoadAllProductCategory();

            List<BasProductCateEntity> rows = dt.FindAll(item => item.Grade == 2);

            foreach (BasProductCateEntity row in rows)
            {
                TreeNode node = CreateNode(row.CateName, false, row.CateCode); 
                tvProductCate.Nodes.Add(node);

                RecursivelyPopulate(dt, node,row);
            }
        }

        private void RecursivelyPopulate(List<BasProductCateEntity> dt, TreeNode node,BasProductCateEntity current)
        {
            List<BasProductCateEntity> rows = dt.FindAll(item => item.Grade == (current.Grade + 1) && item.CateCode.StartsWith(node.Value));
            foreach (BasProductCateEntity row in rows)
            {
                TreeNode treenode = CreateNode(row.CateName, false, row.CateCode);


                node.ChildNodes.Add(treenode);
                RecursivelyPopulate(dt, treenode,row);
            }
        }

        private TreeNode CreateNode(string text, bool expanded, string id)
        {
            TreeNode node;
            node = new TreeNode(text, id);
            node.Expanded = expanded;
            node.SelectAction = TreeNodeSelectAction.Select;
            node.NavigateUrl = ResolveUrl("~/Shared/ProductList.aspx?CateID="+id);
            return node;
        }

        public object SysProductCateEntity { get; set; }
    }
}